package com.kkd.kkdapp.activity;

import com.kkd.kkdapp.BaseApplication;
import com.kkd.kkdapp.R;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.db.app.model.KkdAppInfo;
import com.kkd.kkdapp.gesture.GestureContentView;
import com.kkd.kkdapp.gesture.GestureDrawline.GestureCallBack;
import com.kkd.kkdapp.gesture.LockIndicator;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.AppUtil.onToastDismiss;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * 手势密码设置界面
 * 
 */
public class GestureEditActivity extends Activity implements OnClickListener {
	/** 手机号码 */
	public static final String PARAM_PHONE_NUMBER = "PARAM_PHONE_NUMBER";
	/** 意图 */
	public static final String PARAM_INTENT_CODE = "PARAM_INTENT_CODE";
	/** 首次提示绘制手势密码，可以选择跳过 */
	public static final String PARAM_IS_FIRST_ADVICE = "PARAM_IS_FIRST_ADVICE";
	private RelativeLayout mTextTitle;
	private LockIndicator mLockIndicator;
	private TextView mTextTip;
	private FrameLayout mGestureContainer;
	private GestureContentView mGestureContentView;
	private boolean mIsFirstInput = true;
	private String mFirstPassword = null;
	private boolean isUpdateCodeList = true; // 是否时时更新小view
	protected SystemBarTintManager mTintManager;
	private boolean update; // 为真时是修改手势密码 ，其余情况不能跳过设置界面
	private TextView myblock_top_tv;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent intent = this.getIntent();
		update = intent.getBooleanExtra("update", false);
		setContentView(R.layout.activity_gesture_edit);
		BaseApplication.getInstance().addGestureActivity(this);
		initTintManager();
		setUpViews();
		setUpListeners();
		if (update) {
			mTextTip.setText("请输入新的密码");
			myblock_top_tv.setText("修改手势密码");
			mTextTip.setTextColor(Color.parseColor("#c2c2c2"));
			mTextTitle.setVisibility(View.VISIBLE);
		} else {
			mTextTip.setText("绘制解锁图案");
			myblock_top_tv.setText("设置手势密码");
			mTextTip.setTextColor(Color.parseColor("#c2c2c2"));
			mTextTitle.setVisibility(View.GONE);
		}
		initTextView();
	}

	/**
	 * 初始化为状态栏为纯黑色
	 */
	private void initTintManager() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			setTranslucentStatus(true);
		}

		mTintManager = new SystemBarTintManager(this);
		mTintManager.setStatusBarTintEnabled(true);
		mTintManager.setNavigationBarTintEnabled(true);
		mTintManager.setStatusBarTintResource(R.color.transparent);
		// mTintManager.setTintColor(0x05FF0000);
	}

	@TargetApi(19)
	public void setTranslucentStatus(boolean on) {
		Window win = getWindow();
		WindowManager.LayoutParams winParams = win.getAttributes();
		final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
		if (on) {
			winParams.flags |= bits;
		} else {
			winParams.flags &= ~bits;
		}
		win.setAttributes(winParams);
	}

	private void setUpViews() {
		mTextTitle = (RelativeLayout) findViewById(R.id.text_title);
		mLockIndicator = (LockIndicator) findViewById(R.id.lock_indicator);
		mTextTip = (TextView) findViewById(R.id.text_tip);
		mGestureContainer = (FrameLayout) findViewById(R.id.gesture_container);
		myblock_top_tv = (TextView) findViewById(R.id.myblock_top_tv);
		// 初始化一个显示各个点的viewGroup
		mGestureContentView = new GestureContentView(this, false, "",
				new GestureCallBack() {

					@Override
					public void position(String position) {
						if (isUpdateCodeList) {
							updateCodeList(position);
						}

					}

					@Override
					public void onGestureCodeInput(String inputCode) {
						if (!isInputPassValidate(inputCode)) {
							mTextTip.setText(Html
									.fromHtml("<font color='#c70c1e'>最少链接4个点, 请重新输入</font>"));
							mGestureContentView.clearDrawlineState(0L);
							updateCodeList("");
							isUpdateCodeList = true;
							return;
						}
						if (mIsFirstInput) {
							mFirstPassword = inputCode;
							updateCodeList(inputCode);
							mGestureContentView.clearDrawlineState(0L);
							mIsFirstInput = false;
							mTextTip.setText("请再次绘制手势密码");
							isUpdateCodeList = false;
						} else {
							if (inputCode.equals(mFirstPassword)) {
								showToast("手势密码设置成功");
								mTextTip.setText("您的新解锁图案");
								mGestureContentView.clearDrawlineState(0L);
								GestureEditActivity.this.finish();
								mIsFirstInput = false;
								PreferenceUtils.getInstance().setGesturePW(
										GestureEditActivity.this, inputCode);
								KkdAppInfo appinfo = new KkdAppInfo();
								appinfo.backgroundTime = System
										.currentTimeMillis() / 1000;
								KkdAppInfo.insert(appinfo);
							} else {
								mTextTip.setText(Html
										.fromHtml("<font color='#c70c1e'>与上一次绘制不一致，请重新绘制</font>"));
								mIsFirstInput = true;
								isUpdateCodeList = true;
								updateCodeList("");
								// 左右移动动画
								Animation shakeAnimation = AnimationUtils
										.loadAnimation(
												GestureEditActivity.this,
												R.anim.shake);
								mTextTip.startAnimation(shakeAnimation);
								// 保持绘制的线，1.5秒后清除
								mGestureContentView.clearDrawlineState(0L);
							}
						}

					}

					@Override
					public void checkedSuccess() {
						// TODO Auto-generated method stub

					}

					@Override
					public void checkedFail() {

					}
				});
		// 设置手势解锁显示到哪个布局里面
		mGestureContentView.setParentView(mGestureContainer);
		updateCodeList("");
	}

	private void setUpListeners() {
		mTextTitle.setOnClickListener(this);
	}

	private void updateCodeList(String inputCode) {
		// 更新选择的图案
		mLockIndicator.setPath(inputCode);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.text_title:
			finish();
			break;
		default:
			break;
		}
	}

	private boolean isInputPassValidate(String inputPassword) {
		if (TextUtils.isEmpty(inputPassword) || inputPassword.length() < 4) {
			return false;
		}
		return true;
	}

	public void showToast(String hintLanguage) {

		AppUtil.makeToastForCustomer(this, hintLanguage, new onToastDismiss() {

			@Override
			public void onToastDismiss() {
				finish();
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		AppUtil.closeDialog();
		mGestureContentView.reCycle();
	}

	private TextView textView;
	private long mExitTime;

	private void initTextView() {
		textView = new TextView(this);
		textView.setBackgroundResource(R.drawable.bg_back_toast);
		textView.setText(R.string.homeactivity_exit);
		textView.setGravity(Gravity.CENTER);
		textView.setTextSize(16);
		textView.setTextColor(Color.parseColor("#333333"));
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			if (!update) {
				if ((System.currentTimeMillis() - mExitTime) > 2000) {
					Toast toast = new Toast(GestureEditActivity.this);
					toast.setDuration(Toast.LENGTH_SHORT);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.setView(textView);
					toast.show();
					mExitTime = System.currentTimeMillis();
				} else {
					// 必须退出整个程序
					finish();
					BaseActivity.isNeedUpdateTime = false;
					BaseApplication.getInstance().exitGestureActivity();
					BaseApplication.getInstance().exitKkd();//退出app
				}
			} else {
				finish();
			}

			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
